<script setup lang="ts">


import type {User} from "~/composables/authhooks";
import {Client_PATCH} from "~/utils/httpUtils";
import DataTableTest from "~/components/DataTableTest.vue";

definePageMeta({
  //布局
  layout: 'landing-layout',
  validate: async (route: any) => {
    return true
  }
})
onMounted(() => {
  handleAdminGetUserList()
})
type UserKeys = keyof User;
// const tableHeaders: UserKeys[] = ['_id', 'username', 'role', 'status', 'email', 'balance', 'avatar_url', 'last_login_date', 'inviter_uid', 'nickname', 'register_date', 'wx_openid', 'wx_unionid', 'mobile']
const headers = [
  {title: 'Actions', key: 'actions', sortable: false},
  {
    title: '_id',
    key: '_id',
    align: 'start',
  },
  {
    title: 'username',
    key: 'username',
    align: 'start',
    editable: true,
  },
  {
    title: 'password',
    key: 'password',
    align: 'start',
    editable: false,
  },
  {
    title: 'role',
    key: 'role',
    align: 'start',
    editable: true,
  },
  {
    title: 'status',
    key: 'status',
    align: 'start',
    editable: true,
  },
  {
    title: 'email',
    key: 'email',
    align: 'start',
    editable: true,
  },
  {
    title: 'balance',
    key: 'balance',
    align: 'start',
    editable: true,
  },
  {
    title: 'avatar_url',
    key: 'avatar_url',
    align: 'start',
    editable: true,
  },
  {
    title: 'last_login_date',
    key: 'last_login_date',
    align: 'start',
  },
  {
    title: 'inviter_uid',
    key: 'inviter_uid',
    align: 'start',
  },
  {
    title: 'nickname',
    key: 'nickname',
    align: 'start',
    editable: true,
  },
  {
    title: 'register_date',
    key: 'register_date',
    align: 'start',
  },
  {
    title: 'wx_openid',
    key: 'wx_openid',
    align: 'start',
  },
  {
    title: 'wx_unionid',
    key: 'wx_unionid',
    align: 'start',
  },
  {
    title: 'mobile',
    key: 'mobile',
    align: 'start',
    editable: true,
  },
]

const tableData = ref<User[]>([])

/**
 * 获取用户信息
 */
const handleAdminGetUserList = async () => {
  tableData.value = await Client_GET('/users') as User[]
}
//更新用户状态
const handleAdminUpdateUserStatus = async (uid: string, status: 0 | 1 | 2) => {
  //如果是管理员账户，不允许操作
  if (tableData.value.find(item => item._id === uid)?.username!.includes('admin')) {
    useSnackbarStore().showErrorMessage('管理员账户不允许操作')
    return
  }
  await Client_PATCH(`/users/${uid}`, {status})
  useSnackbarStore().showSuccessMessage(`${status === 0 ? '启用' : '禁用'}成功`)
  //同步更新本地表格数据
  tableData.value = tableData.value.map(item => {
    if (item._id === uid) {
      item.status = status
    }
    return item
  })
}


const editedIndex = ref(-1)
const editedItem = ref<User>({})
const dialogEdit = ref(false)
const dialogDelete = ref(false)


const editItem = (item: any) => {
  editedIndex.value = tableData.value.indexOf(item)
  editedItem.value = Object.assign({}, item)
  dialogEdit.value = true
}

const deleteItem = (item: any) => {
  editedIndex.value = tableData.value.indexOf(item)
  editedItem.value = Object.assign({}, item)
  dialogDelete.value = true
}
const saveEditedItem = async () => {
  await Client_PATCH(`/users/${editedItem.value._id}`, editedItem.value)
  useSnackbarStore().showSuccessMessage('编辑成功')
  dialogEdit.value = false
  editedIndex.value = -1
  editedItem.value = {}
  await handleAdminGetUserList()
}
/**
 * 重置密码为123456
 */
const handleResetPassword = async (uid: string) => {
  await Client_PATCH(`/users/${uid}`, {password: '123456'})
  useSnackbarStore().showSuccessMessage('重置密码为123456成功，请登录尽快修改密码')
}
/**
 * 谨慎操作，从数据库中移除
 */
const deleteItemConfirm = async () => {
  await Client_DELETE(`/users/${editedItem.value._id}`)
  useSnackbarStore().showSuccessMessage('删除成功')
  dialogDelete.value = false
  editedIndex.value = -1
  editedItem.value = {}
  await handleAdminGetUserList()
}

</script>

<template>
  <!--  <data-table-test/>-->
  <!--  <v-table-->
  <!--      fixed-header-->
  <!--  >-->
  <!--    <thead>-->
  <!--    <tr>-->
  <!--      <th v-for="header in tableHeaders" class="text-left">-->
  <!--        {{header.toUpperCase()}}-->
  <!--      </th>-->
  <!--    </tr>-->
  <!--    </thead>-->
  <!--    <tbody>-->
  <!--    <tr v-for="user in tableData">-->
  <!--      <td v-for="key in tableHeaders">-->
  <!--        <v-avatar v-if="key === 'avatar_url'">-->
  <!--          <img :src="user[key]" alt="avatar">-->
  <!--        </v-avatar>-->
  <!--        <v-chip-group v-else-if="key === 'role'">-->
  <!--          <v-chip size="x-small"  v-for="role in user[key]" :class="role === 'admin' ? 'bg-green' : 'bg-gray'">-->
  <!--            {{role}}-->
  <!--          </v-chip>-->
  <!--        </v-chip-group>-->

  <!--        <span v-else-if="key === 'last_login_date'||key === 'register_date'">-->
  <!--          {{new Date(user[key]).toLocaleString()}}-->
  <!--        </span>-->
  <!--      &lt;!&ndash;        显示用户状态 0 正常 1 禁用 3 删除&ndash;&gt;-->
  <!--        <span v-else-if="key === 'status'" class="d-flex">-->
  <!--          <v-chip size="x-small" :color="user[key] === 0 ? 'green' : 'red'">-->
  <!--            {{user[key] === 0 ? '正常' : '禁用'}}-->
  <!--          </v-chip>-->
  <!--          <v-btn @click="handleAdminUpdateUserStatus(user._id,user[key] === 0 ? 1 : 0)" size="x-small" :color="user[key] === 0 ? 'warning' : 'green'">-->
  <!--            {{user[key] === 0 ? '禁用' : '启用'}}-->
  <!--          </v-btn>-->
  <!--        </span>-->
  <!--        <span v-else>-->
  <!--          {{user[key]}}-->
  <!--        </span>-->
  <!--      </td>-->
  <!--    </tr>-->
  <!--    </tbody>-->
  <!--  </v-table>-->
  <v-data-table
      :headers="headers"
      :items="tableData"
      density="compact"
      item-key="output"
  >

    <template v-slot:item="{ item }">
      <tr>
        <td v-for="(headitem,index) in headers">

          <v-avatar v-if="headitem.key === 'avatar_url'">
            <img :src="item[headitem.key]" alt="avatar">
          </v-avatar>
          <v-chip-group v-else-if="headitem.key === 'role'">
            <v-chip size="x-small" v-for="role in item[headitem.key]"
                    :class="role === 'admin' ? 'bg-green' : 'bg-gray'">
              {{ role }}
            </v-chip>
          </v-chip-group>

          <span v-else-if="headitem.key === 'last_login_date'||headitem.key === 'register_date'">
                    {{ new Date(item[headitem.key]).toLocaleString() }}
                  </span>
          <!--          重置密码-->
          <v-btn @click="handleResetPassword(item._id)" size="x-small" color="warning" v-else-if="headitem.key === 'password'">
            重置
          </v-btn>
          <!--        显示用户状态 0 正常 1 禁用 3 删除-->
          <span v-else-if="headitem.key === 'status'" class="d-flex">
                    <v-chip size="x-small" :color="item[headitem.key] === 0 ? 'green' : 'red'">
                      {{ item[headitem.key] === 0 ? '正常' : '禁用' }}
                    </v-chip>
                    <v-btn @click="handleAdminUpdateUserStatus(item._id,item[headitem.key] === 0 ? 1 : 0)"
                           size="x-small"
                           :color="item[headitem.key] === 0 ? 'warning' : 'green'">
                      {{ item[headitem.key] === 0 ? '禁用' : '启用' }}
                    </v-btn>
                  </span>
          <v-sheet v-else-if="headitem.key === 'actions'">
            <v-icon @click="editItem(item)" color="primary" class="mr-2">
              mdi-pencil
            </v-icon>
            <!--            编辑对话框-->
            <v-dialog
                v-model="dialogEdit"
                max-width="60%"
                opacity="0.1"
            >
              <v-card>
                <v-card-title>
                  <span class="text-h5">编辑</span>
                </v-card-title>

                <v-card-text>
                  <v-container>
                    <v-row>
                      <v-col
                          cols="12"
                          md="6"
                          v-for="(headitem,index) in headers.filter(item => item.editable)"
                      >
                        <v-label>{{ headitem.title }}</v-label>
                        <v-text-field
                            v-model="editedItem[headitem.key]"
                        ></v-text-field>
                      </v-col>
                    </v-row>
                  </v-container>
                </v-card-text>

                <v-card-actions>
                  <v-spacer></v-spacer>
                  <v-btn
                      color="blue-darken-1"
                      variant="text"
                      @click="dialogEdit = false"
                  >
                    取消
                  </v-btn>
                  <v-btn
                      color="blue-darken-1"
                      variant="text"
                      @click="saveEditedItem"
                  >
                    保存
                  </v-btn>
                </v-card-actions>
              </v-card>
            </v-dialog>
            <v-icon @click="deleteItem(item)" color="error">mdi-delete</v-icon>
            <v-dialog v-model="dialogDelete" max-width="40%" opacity="0.1">
              <v-card>
                <v-card-title class="text-h6 ma-2">这将永久删除用户，所有用户数据都将丢失，是否继续？</v-card-title>
                <v-card-actions>
                  <v-spacer></v-spacer>
                  <v-btn color="blue-darken-1" variant="text" @click="dialogDelete = false">取消</v-btn>
                  <v-btn color="warning" variant="flat" size="small" @click="deleteItemConfirm">确认删除</v-btn>
                  <v-spacer></v-spacer>
                </v-card-actions>
              </v-card>
            </v-dialog>
          </v-sheet>

          <span v-else>
                    {{ item[headitem.key] }}
                  </span>

        </td>

      </tr>
    </template>

    <!--    <template v-slot:no-data>-->
    <!--      <v-btn-->
    <!--          color="primary"-->
    <!--          @click="initialize"-->
    <!--      >-->
    <!--        Reset-->
    <!--      </v-btn>-->
    <!--    </template>-->
  </v-data-table>
</template>

<style scoped lang="scss">

</style>